package demo11;

import java.nio.channels.AsynchronousSocketChannel;
import java.util.Arrays;

public class Solution {

    //堆排
    public void heapSort(int[] arr) {
        //创建一个大根堆
        createBigHeap(arr);
        for(int i = arr.length - 1; i > 0; i--) {
            swap(arr, 0, i);
            adjustDown(arr, 0, i);
        }
    }

    private void createBigHeap(int[] arr) {
        //从最后一颗子树的父节点开始向下调整
        int len = arr.length;
        for(int parent = (len - 1 - 1) / 2; parent >= 0; parent--) {
            adjustDown(arr, parent, len);
        }
    }

    private void adjustDown(int[] arr, int parent, int len) {
        int child = parent * 2 + 1;
        while(child < len) {
            if(child + 1 < len && arr[child + 1] > arr[child]) {
                child++;
            }
            if(arr[child] > arr[parent]) {
                swap(arr, child, parent);
                parent = child;
                child = child * 2 + 1;
            } else {
                break;
            }
        }
    }

    private void swap(int[] arr, int child, int parent) {
        int tmp = arr[child];
        arr[child] = arr[parent];
        arr[parent] = tmp;
    }



}

class Main {
    public static void main(String[] args) {
        int[] arr = {10, 7, 4, 8, 9,3,2,5};
        Solution solution = new Solution();
        solution.heapSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
